﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;


namespace multi_task_async
{
    class Homework
    {
        private int id_;
        public Homework(int id) { id_ = id; }
        public async Task<int> do_work()
        {
            string tid = Thread.CurrentThread.ManagedThreadId.ToString();
            System.Console.WriteLine("Begin Homework {0} at {1}", id_, tid);
            // 这里将会异步的执行work函数，且在work执行完成后，切换回来继续执行剩余部分
            int ret = await Task<int>.Run(new Func<int>(work));
            System.Console.WriteLine("End Homework {0}", id_);
            return ret;
        }
        private int work() {
            int count = id_;
            while (count-- > 0)
            {
                System.Threading.Thread.Sleep(500);
            }
            return id_;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 使用async&await异步的启动4个耗时的作业任务。
            Homework hw1 = new Homework(7);
            Homework hw2 = new Homework(8);
            Homework hw3 = new Homework(9);
            Homework hw4 = new Homework(100);
            // 依次执行四个作业任务
            Task<int> task1 = hw1.do_work();
            Task<int> task2 = hw2.do_work();
            Task<int> task3 = hw3.do_work();
            Task<int> task4 = hw4.do_work();
            // 等待计算结果
            System.Console.WriteLine("Return from Task3 > {0}",task3.Result);

            System.Console.ReadKey();
        }
    }
}